package org.changchen.fgt.service.impl;

import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.changchen.fgt.config.SourceApiConfig;
import org.changchen.fgt.constant.FromCodeColorEnum;
import org.changchen.fgt.dto.ApiInfo;
import org.changchen.fgt.dto.VideoDetail;
import org.changchen.fgt.dto.VideoInfo;
import org.changchen.fgt.dto.VideoPlayInfo;
import org.changchen.fgt.service.FilmService;
import org.changchen.fgt.service.SourceParseService;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class FilmServiceImpl implements FilmService{
	
	
	@Resource
	private SourceParseService sourceParseService;
	
	
	@Override
	public List<VideoInfo> getVideoList(String word){		
		
		// 获取资源
		List<VideoInfo> videoList = new ArrayList<>();
		
		// 并行处理
		SourceApiConfig.SRC_CONFIG.entrySet().parallelStream().forEach(item -> {
			
			ApiInfo apiInfo = item.getValue();
			
			List<VideoInfo> subVideoList = this.getSubVideoList(apiInfo.getUrl(), apiInfo.getDataType(), word);
			if(CollectionUtils.isNotEmpty(subVideoList)) {
				subVideoList.forEach(video -> {
					video.setVodPlayFrom(item.getKey());
					video.setVodFromName(apiInfo.getName());
					// 颜色
					video.setFromShort(apiInfo.getName().substring(0, 1));
					video.setFromColor(FromCodeColorEnum.getColor(item.getKey()));
					// 是否完结
					video.setFinished(this.isFinished(video));
				});
				videoList.addAll(subVideoList);
			}
			
		});
		
		
		// 根据更新时间排序，最新在最上
		videoList.sort((video1, video2) -> {return video2.getVodTime().compareTo(video1.getVodTime());});
		
		return videoList;		
		
	}

	/**
	 * 视频是否完结
	 * @param video
	 * @return
	 */
	private Boolean isFinished(VideoInfo video) {
		// vodRemarks 包含 完 或者 全 或者 更新时间 在七天前
		LocalDateTime lastUpdateTime = LocalDateTime.parse(video.getVodTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		return video.getVodRemarks().contains("完") || video.getVodRemarks().contains("全") || lastUpdateTime.isBefore(LocalDateTime.now().minusDays(7));
	}
	
	
	/**   
	 * @Title:      getSubVideoList   
	 * @Description:获取各个资源的列表   
	 * @param:      @param url
	 * @param:      @param word
	 * @param:      @return      
	 * @return:     List<VideoInfo>      
	 * @throws   
	 */
	private List<VideoInfo> getSubVideoList(String url, String dataType, String word){	

		if(SourceApiConfig.DATA_TYPE_JSON.equals(dataType)) {
			return sourceParseService.getVideoListFromJson(url, word);
		}		
		
		return sourceParseService.getVideoListFromXml(url, word);
	}
	

	@Override
	public VideoDetail getVideoDetail(String code, Integer vodId) {
		
		ApiInfo apiInfo = SourceApiConfig.SRC_CONFIG.get(code);
		
		VideoDetail detail = null;

		if(SourceApiConfig.DATA_TYPE_JSON.equals(apiInfo.getDataType())) {
			detail = sourceParseService.getVideoDetailFromJson(code, vodId);
		} else  {
			detail = sourceParseService.getVideoDetailFromXml(code, vodId);
		}

		// 播放地址过滤不是 m3u8 后缀的url
		List<VideoPlayInfo> playList = detail.getPlayList();
		if(CollectionUtils.isNotEmpty(playList)) {
			playList.removeIf(item -> !item.getUrl().endsWith("m3u8"));
			detail.setPlayList(playList);
		}
		
		return detail;
	}
	
	
	@Override
	public ModelAndView downloadM3u8(String code, Integer vodId, HttpServletResponse response) {
		
		try {
			
			VideoDetail detail = this.getVideoDetail(code, vodId);
			
			// 播放地址解析
			List<VideoPlayInfo> playSources = detail.getPlayList();
			
			// 响应格式设置
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");
			String filename = String.format("%s.%s.m3u8", detail.getName(), code);
			response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
			
			ModelAndView model = new ModelAndView("m3u8");
			model.addObject("name",detail.getName());
			model.addObject("playList", playSources);
			
			return model;
			
		} catch (Exception e) {
			log.error("请求出错啦，请稍后再试, {}", e);
		}
		
		return null;
	}
	
	
}
